<template>
	<div class="advert_container">
		<div class="advert_header">
			<el-select v-model="searList.status" style="width: 200px" placeholder="请选择广告状态">
				<el-option v-for="(item,index) in advertStatus" :key="index" :label="item.name" :value="item.value" />
			</el-select>
			<el-select v-model="searList.adType" style="width: 200px" placeholder="请选择广告类型">
				<el-option v-for="(item,index) in advertType" :key="index" :label="item.name" :value="item.value" />
			</el-select>
			<el-button type="primary" icon="el-icon-search" @click='search()' style="margin-left: 5px;">查找</el-button>
			<el-button type="primary" icon="el-icon-edit" @click='fixAdvert("add")'>添加</el-button>
		</div>
		<el-table v-loading="loading" :data="advertList" size="small" element-loading-text="正在查询中。。。" border fit
			highlight-current-row>
			<el-table-column align="center" label="广告ID" prop="id" sortable />
			<el-table-column align="center" label="广告标题" prop="title" />
			<el-table-column align="center" label="广告类型" prop="adType">
				<template slot-scope="scope">
					<el-tag>{{getAdvertType(scope.row.adType)}}</el-tag>
				</template>
			</el-table-column>
			<el-table-column align="center" label="广告状态" prop="status">
				<template slot-scope="scope">
					<el-tag>{{getAdvertStatus(scope.row.status)}}</el-tag>
				</template>
			</el-table-column>
			<el-table-column align="center" label="广告图片" prop="imgUrl">
				<template slot-scope="scope">
					<img :src="scope.row.imgUrl" width="80" />
				</template>
			</el-table-column>
			<el-table-column align="center" label="活动链接" prop="url" />
			<el-table-column align="center" label="操作" width="200" class-name="small-padding fixed-width">
				<template slot-scope="scope">
					<el-button type="primary" size="mini" @click='fixAdvert("edit",scope.row)'>编辑</el-button>
					<el-button type="danger" size="mini" @click='delAdvert(scope.row)'>删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<!-- 添加或编辑 -->
		<el-dialog :visible.sync="dialogVisible" :title="title">
			<el-form ref="advertForm" :rules="rules" :model="advertForm" status-icon label-position="left"
				label-width="100px" style="width: 400px; margin-left:50px;">
				<el-form-item label="广告标题" prop="title">
					<el-input v-model="advertForm.title" />
				</el-form-item>
				<el-form-item label="广告图片" prop="imgUrl">
					<el-upload :action="uploadPath" :show-file-list="false" :on-success="handleAvatarSuccess"
						:before-upload="beforeAvatarUpload" class="avatar-uploader">
						<img v-if="advertForm.imgUrl" :src="advertForm.imgUrl" class="avatar">
						<i v-else class="el-icon-plus avatar-uploader-icon"></i>
					</el-upload>
				</el-form-item>
				<el-form-item label="广告类型" prop="title">
					<el-select v-model="advertForm.adType" style="width: 200px" placeholder="请选择广告类型">
						<el-option v-for="(item,index) in advertType" :key="index" :label="item.name"
							:value="item.value" />
					</el-select>
				</el-form-item>
				<el-form-item label="广告状态" prop="title">
					<el-select v-model="advertForm.status" style="width: 200px" placeholder="请选择广告状态">
						<el-option v-for="(item,index) in advertStatus" :key="index" :label="item.name"
							:value="item.value" />
					</el-select>
				</el-form-item>
				<el-form-item label="关联1">
					<el-cascader :options="options" :props="{ checkStrictly: true }" v-model="categoryTitle"
						placeholder="关联类目、商品" filterable @change="handleLink" />
				</el-form-item>
				<el-form-item label="关联2">
					<el-select v-model="functionName" placeholder="关联功能页面" @change="handleLink2">
						<el-option v-for="item in functionPages" :key="item.value" :label="item.label"
							:value="item.value" />
					</el-select>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="closeDialog()">取消</el-button>
				<el-button v-if="title === '创建'" type="primary" @click="addAdvert('advertForm')">确定</el-button>
				<el-button v-else type="primary" @click="updatAdvert('advertForm')">确定</el-button>
			</div>
		</el-dialog>
		<!-- 分页 -->
		<el-footer v-if="advertList.length>0" class="border-top d-flex align-items-center px-0  bg-white"
			style="margin-top: 36px;">
			<div style="flex: 1;" class="px-2">
				<el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
					:current-page.sync="searList.pageNo" :page-sizes="[10, 20, 30, 50, 100]" :page-size="searList.limit"
					layout="total, sizes, prev, pager, next, jumper" :total="total">
				</el-pagination>
			</div>
		</el-footer>
	</div>
</template>

<script>
	import {
		getAdvert,
		deleteAdvert,
		getAdCategory,
		uploadPath,
		createAdvert,
		updateAdvert
	} from '../api.js'
	export default {
		data() {
			return {
				searList: {
					pageNo: 1,
					limit: 20,
					status: '',
					adType: ''
				},
				total: 1,
				uploadPath,
				advertStatus: [{
					name: "冻结",
					value: 0,
				}, {
					name: "激活",
					value: 1
				}, {
					name: "全部",
					value: ''
				}],
				advertType: [{
					name: "轮播",
					value: 1,
					id: 3
				}, {
					name: "分类精选",
					value: 2,
					id: 1
				}, {
					name: "横幅",
					value: 3,
					id: 3
				}, {
					name: "首页轮播下5按钮",
					value: 4,
					id: 1
				}, {
					name: "全部",
					value: ""
				}],
				loading: false,
				advertList: [],
				options: [],
				title: '创建',
				dialogVisible: false,
				functionName: undefined,
				advertForm: {
					addType: undefined,
					title: undefined,
					url: undefined,
					imgUrl: undefined,
					status: undefined,
					color: undefined
				},
				categoryTitle: undefined,
				functionPages: [{
					value: "/pages/groupshop/list",
					label: "团购列表"
				}],
				rules: {
					title: [{
						required: true,
						message: "广告标题不能为空",
						trigger: "blur"
					}],
					imgUrl: [{
						required: true,
						message: "广告图片不能为空",
						trigger: "blur"
					}],
					adType: [{
						required: true,
						message: "请选择广告类型",
						trigger: "blur"
					}],
					status: [{
						required: true,
						message: "请选择广告状态",
						trigger: "blur"
					}]
				},
			}
		},
		methods: {
			getData() {
				this.loading = true;
				getAdvert(this.searList).then((res) => {
					// console.log(res.data.data)
					this.advertList = res.data.data.items;
					this.total = res.data.data.total;
					this.loading = false;
				})
			},
			handleSizeChange(val) { //每页条数
				this.searList.limit = val
				this.getData();
			},
			handleCurrentChange(val) { //前往第几页
				this.searList.pageNo = val
				// console.log(val)
				this.getData()
			},
			// 搜索
			search() {
				this.searList.pageNo = 1;
				this.getData()
			},
			getAdvertType(value) {
				return this.advertType[value - 1]["name"]
			},
			getAdvertStatus(value) {
				return this.advertStatus[value]["name"]
			},
			// 删除
			delAdvert(value) {
				this.$confirm("此操作将永久删除该广告--" + value.title + "--, 是否继续?", "提示", {
					confirmButtonText: "确定",
					cancelButtonText: "取消",
					type: "warning"
				}).then(() => {
					deleteAdvert(value.adType, value.id).then((res) => {
						this.$message.success("删除成功");
						let index = this.advertList.indexOf(value);
						this.advertList.splice(index, 1);
					})
				})
			},
			// 初始化表单
			fixAdvert(type, value) {
				this.dialogVisible = true;
				this.getOptions()
				if (type === 'add') {
					this.title = "创建"
					this.advertForm = {
						addType: undefined,
						title: undefined,
						url: undefined,
						imgUrl: undefined,
						status: undefined,
						color: undefined
					}
					this.functionName = undefined;
					this.categoryTitle = undefined;
				} else {
					this.title = "编辑"
					this.advertForm = Object.assign({}, value);
					if (this.advertForm.url.indexOf("tid") >= 0) {
						this.categoryTitle = "C_" + this.advertForm.url.replace(/[^0-9]/gi, "");
					} else {
						this.categoryTitle = "G_" + this.advertForm.url.replace(/[^0-9]/gi, "");
					}
				}
				if (this.$refs.advertForm != undefined) {
					this.$refs.advertForm.resetFields(); //form表单的dom渲染完在执行this.$refs.advertForm.resetFields()，去除验证
				}
			},
			// 关闭弹出框
			closeDialog() {
				this.dialogVisible = false;
			},
			// 获取
			getOptions() {
				getAdCategory().then((res) => {
					// console.log()
					this.options = this.getTreeData(res.data.data)
				})
			},
			// 处理数据最有一级空白无数据的问题，使用递归的方式，将最底层中的 children设为undefined
			getTreeData(data) {
				for (var i = 0; i < data.length; i++) {
					if ('children' in data[i]) {
						if (data[i].children.length < 1) {
							// children若为空数组，则将children设为undefined
							data[i].children = undefined;
						} else {
							// children若不为空数组，则继续 递归调用 本方法
							this.getTreeData(data[i].children);
						}
					}
				}
				return data;
			},
			handleLink(e) {
				// console.log(e)
				if (e === undefined || e === null) {
					return;
				}
				this.functionName = undefined;
				let id = e[e.length - 1]; //选择最后一个
				if (this.categoryTitle.length < 3) {
					this.$message.error("请关联第三级类目或者商品");
					return;
				}
				// console.log(id)
				if (id.indexOf("C") != -1) {
					this.advertForm.url = "/pages/product/list?tid=" + id.substring(2)
				} else {
					this.advertForm.url = "/pages/product/detail?id=" + id.substring(3)
				}
				// console.log(this.advertForm.url)
			},
			handleLink2(e) {
				if (e === undefined || e === null) {
					return;
				}
				// if(!e){
				this.categoryTitle = undefined;
				this.advertForm.url = e;
				// }
			},
			addAdvert(formName) {
				this.$refs[formName].validate((valid) => {
					this.advertForm.color = "rgb(122, 194, 182)";
					if (valid && this.isCheck()) {
						createAdvert(this.advertForm).then((res) => {
							// console.log(res)
							if (res.data.errno == 200) {
								this.getData();
								this.dialogVisible = false;
								this.$message.success("创建成功");
							} else {
								this.dialogVisible = false;
								this.$message.error(res.data.errmsg);
								this.getData();
							}
						})
					} else {
						return false;
					}
				})
			},
			updatAdvert(formName) {
				this.$refs[formName].validate((valid) => {
					this.advertForm.color = "rgb(122, 194, 182)";
					if (valid && this.isCheck()) {
						updateAdvert(this.advertForm).then((res) => {
							console.log(res)
							if (res.data.errno == 200) {
								this.getData();
								this.dialogVisible = false;
								this.$message.success("更新广告成功");
							} else {
								this.dialogVisible = false;
								this.$message.error(res.data.errmsg);
								this.getData();
							}
						})
					} else {
						return false;
					}
				})
			},
			isCheck() {
				if (this.functionName === undefined) {
					if (this.categoryTitle === undefined || this.categoryTitle.length < 3) {
						this.$message.error("请关联三级目录或者商品");
						return false;
					}
					for (let i = 0; i < this.advertType.length; i++) {
						const item = this.advertType[i];
						if (item.value === this.advertForm.adType) {
							if (this.categoryTitle.length === 4 && item.id === 1) {
								this.$message.error("此类广告只能关联三级类目");
								return false;
							} else if (this.categoryTitle.length === 3 && item.id === 3) {
								this.$message.error("此类广告只能关联商品");
								return false;
							}
						}
					}
				}
				return true;
			},
			handleAvatarSuccess(res, file) {
				this.advertForm.imgUrl = URL.createObjectURL(file.raw);
			},
			beforeAvatarUpload(file) {
				const isJPG = file.type === "image/jpeg";
				const isLt2M = file.size / 1024 / 1024 < 2;

				if (!isJPG) {
					this.$message.error("上传头像图片只能是 JPG 格式!");
				}
				if (!isLt2M) {
					this.$message.error("上传头像图片大小不能超过 2MB!");
				}
				return isJPG && isLt2M;
			}
		},
		created() {
			this.getData()
		}
	}
</script>

<style>
	.advert_container {
		width: 100%;
		height: 660px;
		overflow-x: auto;
		overflow-y: auto;
		padding: 20px;
	}

	.advert_header>* {
		margin-left: 4px;
	}

	.advert_header {
		padding-bottom: 10px;
	}

	.avatar-uploader .el-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
	}

	.avatar-uploader .el-upload:hover {
		border-color: #409EFF;
	}

	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		line-height: 178px;
		text-align: center;
	}

	.avatar {
		width: 145px;
		height: 145px;
		display: block;
	}
</style>
